package cn.lnexin.handler;

import java.util.List;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.LastHttpContent;
import io.netty.handler.codec.http.QueryStringDecoder;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import io.netty.util.CharsetUtil;

/**
 * 接收激活数据
 * 
 * @Description:TODO
 * @author Daniel
 * @date 2018年1月17日 下午4:44:09
 */
public class IPProxyHandler extends ChannelInboundHandlerAdapter {
	static Logger log = LogManager.getLogger(IPProxyHandler.class);
	private SessionContextManager manager;
	private final AttributeKey<Long> timestamp = AttributeKey.valueOf("timestamp");
	
	@Override
	public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
		log.info("[{}] is added.", ctx.channel().id().asLongText());
		super.handlerAdded(ctx);
	}
	
	// 回话关闭,事件失效
	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		// TODO Auto-generated method stub
		// manager.getSession().remove(ctx.channel().id().asLongText());
		log.info("this channel colse:{}", ctx.channel().id().asLongText());
		super.channelInactive(ctx);
	}
	
	// 读消息,业务处理事件的入口
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		log.info("yeah,i reading...");
		
		// 测试信道中保存状态消息,如消息处理的开如时间
		// Attribute<Long> attr_dt = ctx.channel().attr(timestamp);
		// attr_dt.set(System.currentTimeMillis());
		//
		// SessionContext sctx = new SessionContext();
		// sctx.setCtx(ctx);
		// sctx.setChannelId(ctx.channel().id());
		// sctx.setSessionActiveTime("" + System.currentTimeMillis());
		// manager.getSession().put(sctx.getChannelId().asLongText(), sctx);
		log.info("{} req time {}", ctx.channel().id().asLongText(), System.currentTimeMillis());
		
		reqProcess(ctx, msg);
		// reqProcess(ctx, manager, msg);
		
		super.channelRead(ctx, msg);
		
	}
	
	private QueryStringDecoder qdecoder = null;
	private String uri = "";// http uri
	private String url = "";// http url
	private Map<String, List<String>> httpReqParams = null;// http请求参数
	
	private String reqProcess(ChannelHandlerContext ctx, Object msg) {
		System.out.println(ctx.toString());
		System.out.println(msg.toString());
		StringBuilder buf = new StringBuilder(); 
		String decode_message = "";  
		   if (msg instanceof HttpRequest) {// http请求头  
	            HttpRequest req = (HttpRequest) msg;  
	            url = req.getUri();  
	            if (url.equals("/favicon.ico")) {  
	                ctx.close();  
	                return "0";  
	            }  
	            if(!url.equals("/billing")){  
	                ctx.close();  
	                return "0";  
	            }  
	            //if (is100ContinueExpected(req)) {  
	               // ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));  
	           // }  
	            qdecoder = new QueryStringDecoder(url);  
	            httpReqParams = qdecoder.parameters();  
	            uri = qdecoder.path();  
	            /* TODO：身份认证 
	             * if(qdecoder.parameters().containsKey("crendial")){ 
	             * crendial=(String 
	             * )qdecoder.parameters().get("crendial").get(0).toUpperCase(); } 
	             */  
	              
	        } else if (msg instanceof HttpContent) { // http请求体  
	              
	            HttpContent httpContent = (HttpContent) msg;  
	            ByteBuf content = httpContent.content();  
	            if (content.isReadable()) {  
	                String chunk_message=content.toString(CharsetUtil.UTF_8);  
	                         buf.append(chunk_message);  
	            }  
	              
	               if (!(msg instanceof LastHttpContent)) {//<span style="color:#FF0000;">不是最后一个chunk包块，此项非常 重要，当http分多片传输时，需要将多块内容合并</span>  
	                return "0";  
	                   }else{  
	                decode_message= buf.toString(); //  
	                log.info(decode_message);  
	                  }  
	               
	            if (msg instanceof LastHttpContent) {  
	                //LastHttpContent trailer = (LastHttpContent) msg;  
	                  
	                String sessionId=ctx.channel().id().asLongText();  
	                System.out.println("请求"+decode_message);  
	                System.out.println("请求参数"+httpReqParams);  
	                System.out.println("请求地址"+uri);  
	                System.out.println("会话Id"+sessionId);  
	                //<span style="color:#FF0000;">TODO：模拟发送请求消息给后端处理,可以放入消息队列，ctx对象进入会话保持（Map对象）中，等消息队列中处理完成后，恢复会话，并完成消息应答。</span>  
	                  
	            }  
	              
	        }
		return decode_message;  
	}
	
}
